package com.yj.auto.plugin.log4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.handler.Handler;
import com.jfinal.kit.HandlerKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.druid.IDruidStatViewAuth;

public class Log4jViewHandler extends Handler {

	private IDruidStatViewAuth auth;
	private String visitPath = "/log4j";

	public Log4jViewHandler(String visitPath, IDruidStatViewAuth log4jViewAuth) {
		if (StrKit.isBlank(visitPath))
			throw new IllegalArgumentException("visitPath can not be blank");
		if (log4jViewAuth == null)
			throw new IllegalArgumentException("log4jViewAuth can not be null");

		visitPath = visitPath.trim();
		if (!visitPath.startsWith("/"))
			visitPath = "/" + visitPath;
		this.visitPath = visitPath;
		this.auth = log4jViewAuth;
	}

	@Override
	public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
		if (target.startsWith(visitPath)) {
			if (!auth.isPermitted(request)) {
				throw new IllegalArgumentException("log4jViewAuth nopermit");
			}
			try {
				new Log4jServlet().service(request, response);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}

		} else {
			next.handle(target, request, response, isHandled);
		}
	}

}
